package service

import (
	dao "go-bluebell/dao/mysql"
	"go-bluebell/model"
	"go-bluebell/utils"
)

func Register(registerUser model.RegisterUser) error {
	// 判断用户是否存在
	exist, err := dao.CheckUserExist(registerUser.Username)

	if exist {
		return model.ErrorUserExist
	}

	// 生成 UID
	id := utils.GenID()

	user := &model.User{
		UserID:   id,
		Username: registerUser.Username,
		Password: registerUser.Password,
		Email:    registerUser.Email,
	}
	// 保存用户信息至数据库
	dao.Register(user)

	return err
}

// 登录并返回 Token

func Login(LoginUser model.LoginUser) (user *model.User, token string, err error) {
	// 登录逻辑
	user = &model.User{
		Username: LoginUser.Username,
		Password: LoginUser.Password,
	}

	// 这里 user 是指针，所以可以拿到 user.UserID
	err = dao.Login(user)
	if err != nil {
		return nil, "", err
	}

	// 生成并返回 JWT Token
	token, err = utils.GenToken(user.UserID, user.Username)
	if err != nil {
		return nil, "", err
	}
	return

}
